#
# peerscape.daemon.cache
#
# Copyright 2009 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Profile Cache

This agent automatically subscribes to all the personal profiles
appearing in the Peerscape Users dataset.  It is not part of the
daemon's functionality.  Run it from the top level of the source tree
like this:

    python -m peerscape.daemon.cache

This writes log messages to "new-users.log".
"""

import time
import logging

from peerscape import DB, PATH
from peerscape.daemon.register import IID

LOGFILE = 'new-users.log'

class CachingAgent(object):
    def __init__(self, path):
        self.path = path

    def loop(self):
        self.init()
        while True:
            try:
                self.update()
                time.sleep(1)
            except Exception:
                logging.exception('Exception in caching agent:')
                time.sleep(60)

    def init(self):
        self.db = DB(self.path)
        self.db.subscribe(IID)
        self.mark = self.db.get_local_info('caching_agent:mark', 0)

    def update(self):
        iids = self.db.list(IID, '/people', last_mark=self.mark)
        mark = self.db.get_last_mark()

        for iid in iids:
            info = self.db.get_json(IID, ['people', iid])
            if info:
                name = info.get('name', '<no name?!?>')
                if 'updated' in info:
                    logging.info('Updated user: %s (%s)', iid, name)
                else:
                    logging.info('New user: %s (%s)', iid, name)
                    self.db.subscribe(iid)

        if iids:
            self.mark = mark
            self.db.set_local_info('caching_agent:mark', mark)

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO,
                        filename=LOGFILE,
                        format='%(asctime)s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    try:
        agent = CachingAgent(PATH)
        agent.loop()
    except KeyboardInterrupt:
        pass
